package com.lostreseditores.sabersai.dataaccess.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.persistence.EntityManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.ejb.HibernateEntityManager;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.impl.SessionImpl;

import com.lostreseditores.sabersai.dataaccess.sessionFactory.HibernateSessionFactory;
import com.lostreseditores.sabersai.model.Estudiante;


public class EstudianteDAO implements IEstudianteDAO {
    private static final Log log = LogFactory.getLog(EstudianteDAO.class);

    // property constants
    //public static final String  ESTUCODIGOV = "estucodigov";
    public static final String ESTUCODIGOV = "estucodigov";

    //public static final String  ESTUDOCUMV = "estudocumv";
    public static final String ESTUDOCUMV = "estudocumv";

    //public static final String  ESTUEMAILV = "estuemailv";
    public static final String ESTUEMAILV = "estuemailv";

    //public static final Integer  ESTUIDN = "estuidn";
    public static final String ESTUIDN = "estuidn";

    //public static final String  ESTUNOMBREV = "estunombrev";
    public static final String ESTUNOMBREV = "estunombrev";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }
    
	public Connection getConnection(final EntityManager em) {
		HibernateEntityManager hem = (HibernateEntityManager) em;
		SessionImplementor sim = (SessionImplementor) hem.getSession();
		return sim.connection();
	}
	

    /**
    *
    * @param Instance
    *            Estudiante Instance to persist
     * @return 
    * @throws RuntimeException
    *             when the operation fails
    */
    public Estudiante save(Estudiante instance) {
        log.debug("saving Estudiante instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
            return instance;
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
    
    public Long findTotalNumberCalificacion() {
        log.debug("finding Calificacion count");

        try {
            String queryString = "select count(*) from Calificacion model";
            Query queryObject = getSession().createQuery(queryString);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }

    /**
    * @param Instance
    *            Estudiante Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(Estudiante instance) {
        log.debug("deleting Estudiante instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
    *
    * @param Instance
    *            Estudiante Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(Estudiante instance) {
        log.debug("updating Estudiante instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public Estudiante findById(Integer id) {
        log.debug("finding Estudiante instance with id: " + id);

        try {
            Estudiante instance = (Estudiante) getSession()
                                                   .get(Estudiante.class, id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding Estudiante failed", re);
            throw re;
        }
    }
    

    public List<Estudiante> findByExample(Estudiante instance) {
        log.debug("finding Estudiante instance by example");

        try {
            List results = getSession().createCriteria("Estudiante")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  Estudiante entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< Estudiante> found by query
        */
    public List<Estudiante> findByProperty(String propertyName, Object value) {
        log.debug("finding Estudiante instance with property: " + propertyName +
            ", value: " + value);

        try {
            String queryString = "from Estudiante as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<Estudiante> findByEstucodigov(Object estucodigov) {
        return findByProperty(ESTUCODIGOV, estucodigov);
    }

    public List<Estudiante> findByEstudocumv(Object estudocumv) {
        return findByProperty(ESTUDOCUMV, estudocumv);
    }

    public List<Estudiante> findByEstuemailv(Object estuemailv) {
        return findByProperty(ESTUEMAILV, estuemailv);
    }

    public List<Estudiante> findByEstuidn(Object estuidn) {
        return findByProperty(ESTUIDN, estuidn);
    }

    public List<Estudiante> findByEstunombrev(Object estunombrev) {
        return findByProperty(ESTUNOMBREV, estunombrev);
    }

    /**
    * Find all Estudiante entities.
    *
    * @return List<Estudiante> all Estudiante instances
    */
    public List<Estudiante> findAll() {
        log.debug("finding all Estudiante instances");

        try {
            String queryString = "from Estudiante";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<Estudiante> findByCriteria(String whereCondition) {
        log.debug("finding Estudiante " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from Estudiante model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<Estudiante> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in Estudiante failed", re);
            throw re;
        }
    }

    public List<Estudiante> findPageEstudiante(String sortColumnName,
        boolean sortAscending, int startRow, int maxResults) {
        log.debug("finding Estudiante findPageEstudiante");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from Estudiante model order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from Estudiante model";

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberEstudiante() {
        log.debug("finding Estudiante count");

        try {
            String queryString = "select count(*) from Estudiante model";
            Query queryObject = getSession().createQuery(queryString);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
	}

    
	public String crearCodigoEstudiante() {

		String codigo = null;

		Connection con = ((SessionImpl) getSession()).connection();

		try {
			CallableStatement cs = con
					.prepareCall("{? = call f_crear_codigo_estudiante()}");
			cs.registerOutParameter(1, Types.VARCHAR);
			cs.execute();
			codigo = cs.getString(1);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return codigo;

	}
		 
}
